package edu.chl.dat255.bluebanana.logic.impl;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import edu.chl.dat255.bluebanana.logic.IScreen;

public class APScreen implements IScreen {
	private static IScreen instance = new APScreen();
	private static Context staticContext;
	private static ContentResolver contentResolver;
	private static Window window;

	private APScreen() {
		// Singleton
	}

	public static IScreen getInstance(Context context) {
		staticContext = context;
		
		contentResolver = staticContext.getContentResolver();

		try {
			window = ((Activity) staticContext).getWindow();
		} catch (ClassCastException e) {
			// 
		}
		
		return instance;
	}

	@Override
	/**
	 * @inheritDoc
	 */
	public void setBrightness(int brightness) {
		window = ((Activity) staticContext).getWindow();
		Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);  
		LayoutParams layoutparams = window.getAttributes();  
		layoutparams.screenBrightness = brightness / (float) 255;  
		window.setAttributes(layoutparams); 
	}
	
	@Override
	/**
	 * @inheritDoc
	 */
	public void setScreenTimeout(int screenTimeout) {
		Settings.System.putInt(contentResolver,
				Settings.System.SCREEN_OFF_TIMEOUT, screenTimeout * 1000);
	}

	@Override
	/**
	 * @inheritDoc
	 */
	public void setAutoBrightness(boolean value) {
		if(value) {
			  Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
					  Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
		} else {
			Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
					  Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
		}
	}
	
	@Override
	/**
	 * @inheritDoc
	 */
	public int getBrightness() {
		int i;
		try {
			i = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
			i = 200;
		}
		return i;
	}
	
	@Override
	/**
	 * @inheritDoc
	 */
	public int getScreenTimeOut() {
		int i;
		try {
			i = Settings.System.getInt(contentResolver, Settings.System.SCREEN_OFF_TIMEOUT);
		} catch (SettingNotFoundException e) {
			i = 30000;
		}
		return i;	}
	
	@Override
	/**
	 * @inheritDoc
	 */
	public boolean isAutoBrightness() {
		int compare;
		try {
			compare = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE);
		} catch (SettingNotFoundException e) {
			compare = 100;
		}
		if (compare == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
			return true;
		}
		return false;
	}
}
